package database;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import main.SettingsHandler;

import org.apache.log4j.Logger;

/**
 * A class that handles installation of the database
 * 
 * 
 */
class HSQLDBInstallHandler implements InstallHandler {
   private final String dbHost;
   private final String dbName;
   private final String dbUser;
   private final String dbPassword;

   HSQLDBInstallHandler(final String dbHost, final String dbName, final String dbUser, final String dbPassword) {
	  this.dbHost = dbHost;
	  this.dbName = dbName;
	  this.dbUser = dbUser;
	  this.dbPassword = dbPassword;
   }

   /**
    * Installs the bot database
    * 
    * @return
    */
   @Override
   public boolean runInstall() {
	  if (!new SettingsHandler().saveDBSettings(dbHost, dbName, dbUser, dbPassword))
		 return false;

	  boolean out = false;
	  Connection con = null;
	  BufferedReader br = null;
	  Statement stmt = null;
	  try {
		 Class.forName("org.hsqldb.jdbc.JDBCDriver").newInstance();

		 con = DriverManager.getConnection("jdbc:hsqldb:file:data/" + dbName, dbUser, dbPassword);

		 if (!con.isClosed()) {
			InputStream is = getClass().getResourceAsStream("/database/hsqlsetup.sql");
			br = new BufferedReader(new InputStreamReader(is));
			out = true;

			String line;
			String code = "";
			while ((line = br.readLine()) != null) {
			   code += line;
			}
			final String[] split = code.split(";");

			stmt = con.createStatement();
			for (String s : split) {
			   try {
				  stmt.execute(s);
			   } catch (final Exception e) {
				  System.err.println(s);
				  Logger.getLogger("Error").error(s, e);
				  out = false;
				  break;
			   }
			}
		 }
	  } catch (final Exception e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			stmt.close();
		 } catch (final Exception e) {
		 }
		 try {
			con.close();
		 } catch (final Exception e) {
		 }
		 try {
			br.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }
}
